from rest_framework.request import Request
from rest_framework.utils.serializer_helpers import ReturnDict


# 获取请求携带的参数，没有该参数就不记录到返回值的字典中
def get_request_data(request: Request, fields: list):
    method = request.method
    ret_data = {}
    if method.upper() == "GET":
        # 地址栏中的数据处理
        for field in fields:
            value = request.query_params.get(field, "")
            if value != "":
                ret_data[field] = value
    else:
        # 请求体中的数据处理
        for field in fields:
            value = request.data.get(field, "")
            if value != "":
                ret_data[field] = value
    return ret_data


# 处理序列化器的错误消息，参数是ser.errors 对象，转成字符串
def handel_ser_errors_to_str(errors: ReturnDict):
    error_msg = ""
    for key, value in errors.items():
        if isinstance(value, list):
            for error_obj in value:
                error_msg += f"{key},{str(error_obj)};"
        elif isinstance(value, str):
            error_msg += f"{value},"

    return error_msg
